<?php

namespace app\api\model\Goods\Speci;
use think\Model;

class Category extends Model
{
    public function getPidAttr($value)
    {
        if($value ==0){
            return ['pid'=>0,'pid_name'=>'顶级分类'];
        }else{
            return Category::field('id,name as pid_name')->find($value);
        }
            //return Category::find($value)['name'];
            //return Category::field('id,name as pid_name')->find($value);
    }
    public function info($id)
    {
        return self::find($id);
    }

    public function getAllCategory()
    {
        $list =self::field('id,pid,name')->where('pid',0)->select()->toArray();
        foreach ($list as $k=>$v){
            $list[$k]['son'][] =self::where('pid',$v['id'])->select()->toArray();
        }
        //$arr =$this->getTree($list);
        return $list;
    }

    function getTree($data, $pId = 0)
    {
        $tree = [];
        foreach ($data as $k => $v) {
            if ($v['pid'] == $pId) {
                $v['son'] = $this->getTree($data, $v['id']);
                $tree[] = $v;
                unset($data[$k]);
            }
        }
        return $tree;
    }

    public function add($data)
    {
        return self::create($data);
    }

    public function index($where, $page, $size)
    {
        return self::where($where)->page($page, $size)->paginate($size);
    }

    public function edit($id, $data)
    {
        return self::where('id', $id)->update($data);
    }

    public function del($id)
    {
        return self::destroy(['id' => $id]);
    }
}
